package echo

import (
	"encoding/json"
	"io"
	"log"
	"net/http"
	"time"
	"ws/server/model"
	"ws/server/websocket/clientManage"
	"ws/server/websocket/validators"

	"github.com/gorilla/websocket"
)

func echoCopy(w http.ResponseWriter, r *http.Request, writerOnly bool) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("Upgrade:", err)
		return
	}
	defer conn.Close()
	//log.Println("打印连接1", conn)
	defer clientManage.RemoveClient(conn) // 确保在函数结束时移除客户端
	clientManage.AddClient(conn)          // 添加新连接的客户端
	for {
		mt, r, err := conn.NextReader()
		if err != nil {
			if err != io.EOF {
				log.Println("NextReader:", err)
			}
			return
		}
		if mt == websocket.TextMessage {
			msg := model.MsgObject{}
			dec := json.NewDecoder(r)
			err := dec.Decode(&msg)
			if err != nil {
				log.Println("Error decoding JSON message:", err)
				continue
			}

			// 检查消息类型是否为订阅请求
			switch msg.Type {
			case "sub":
				clientManage.Subscribe(conn, msg.Topic, msg.TargetCodes)
				// 如果需要响应客户端确认订阅成功，可以在这里添加响应逻辑
			case "unSub":
				clientManage.Unsubscribe(conn, msg.Topic, msg.TargetCodes) // 调用Unsubscribe方法移除订阅
			}
		} else if mt == websocket.BinaryMessage {
			// 处理二进制消息的逻辑，这里省略
		}
		w, err := conn.NextWriter(mt)
		if err != nil {
			log.Println("NextWriter:", err)
			return
		}
		if writerOnly {
			_, err = io.Copy(struct{ io.Writer }{w}, r)
		} else {
			_, err = io.Copy(w, r)
		}
		if err != nil {
			if err == validators.ErrInvalidUTF8 {
				conn.WriteControl(websocket.CloseMessage,
					websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""),
					time.Time{})
			}
			log.Println("Copy:", err)
			return
		}
		err = w.Close()
		if err != nil {
			log.Println("Close:", err)
			return
		}
	}
}

func EchoCopyWriterOnly(w http.ResponseWriter, r *http.Request) {
	echoCopy(w, r, true)
}

func EchoCopyFull(w http.ResponseWriter, r *http.Request) {
	echoCopy(w, r, false)
}
